# -*- coding: utf-8 -*-
import hashlib
import json
import random
import string
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

_GATEWAY = 'http://rui.hzzmdz.com/pay/payment'
_QUERY_GATEWAY = 'http://apitest.hzzmdz.com/pay/payquery'

APP_CONF = {
    'B09_yellows': {  #
        'API_KEY': 'gx9stuil4uggko4lpyx5wiqkcmnmudcq',
        'gateway': 'http://www.chuangye138.com:9002/pay_server/tran_pay',
        'query_gateway': 'http://www.chuangye138.com:9002/pay_server/pay_query?out_trade_no={}',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


def _gen_sign(s):
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest()
    return sign


def generate_sign(d, key):
    s = 'mer_id={}&nonce_str={}&out_trade_no={}&total_fee={}&key={}'.format(
        d['mer_id'], d['nonce_str'], d['out_trade_no'], d['total_fee'], key
    )
    _LOGGER.info("tengpay sign str: %s", s)
    return _gen_sign(s)


def generate_notify_sign(d, key):
    s = 'mer_id={}&out_trade_no={}&pay_type={}&real_fee={}&total_fee={}&key={}'.format(
        d['mer_id'], d['out_trade_no'], d['pay_type'], d['real_fee'], d['total_fee'], key
    )
    _LOGGER.info("tengpay sign str: %s", s)
    return _gen_sign(s)


def verify_notify_sign(params, key):
    sign = params['sign']
    params.pop('sign')
    calculated_sign = generate_notify_sign(params, key)
    if sign.upper() != calculated_sign.upper():
        _LOGGER.info("tengpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 001：微信wap
# 002：微信扫码
# 003：微信公众号
# 005：支付宝wap
# 006：支付宝扫码
# 007：支付宝SDK
# 008：网关支付
# 009：快捷支付
# 010：银联二维码
# 011：QQ扫码
# 012：QQWAP
# 013：京东支付
# 015：收银台
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '001'
    elif service == 'alipay':
        payType = '005'
    elif service == 'qq':
        payType = '012'
    elif service == 'quick':
        payType = '009'
    else:
        payType = '013'
    return payType


def _build_query_string(d):
    s = ''
    for k in d.keys():
        s += '%s=%s&' % (k, d[k])
    return s[:-1]


def create_charge(pay, pay_amount, info):
    service = info.get('service')
    app_id = info['app_id']
    api_key = _get_api_key(app_id)
    parameter_dict = OrderedDict((
        ('mer_id', app_id),
        ('out_trade_no', str(pay.id)),
        ('pay_type', _get_pay_type(service)),
        ('goods_name', 'charge'),
        ('total_fee', str(int(pay_amount * 100))),
        ('callback_url', '{}/pay/api/{}/tengpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, str(pay.id))),
        ('notify_url', '{}/pay/api/{}/tengpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, app_id)),
        ('attach', 'charge'),
        ('nonce_str', ''.join(random.sample(string.ascii_letters + string.digits, 12))),
    ))
    parameter_dict['sign'] = generate_sign(parameter_dict, api_key)
    url = _get_gateway(app_id) + '?' + _build_query_string(parameter_dict)
    _LOGGER.info("tengpay create URL : %s", url)
    response = requests.get(url)
    _LOGGER.info("tengpay create rsp : %s", response.text)
    resp = json.loads(response.text)
    pay_url = resp.get('code_url') or resp.get('code_img_url')
    return {'charge_info': pay_url}


# success
def check_notify_sign(request, app_id):
    api_key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("tengpay notify data: %s", data)
    verify_notify_sign(data, api_key)
    pay_id = data['out_trade_no']
    if not pay_id:
        _LOGGER.error("fatal error, out_trade_no not exists, data: %s" % data)
        raise ParamError('tengpay event does not contain pay ID')

    pay = order_db.get_pay(int(pay_id))
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = str(data['result'])
    trade_no = ''
    total_fee = float(data['real_fee']) / 100.0
    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    if trade_status == '0':
        _LOGGER.info('tengpay check order success, mch_id:%s pay_id:%s' % (mch_id, pay_id))
        order_db.add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    ''' 查询订单 '''
    url = _get_query_gateway(app_id).format(pay_order.id)
    _LOGGER.info('tengpay query data, %s', url)
    response = requests.get(url)
    _LOGGER.info('tengpay query rsp, %s', response.text)
    if response.status_code == 200:
        mch_id = pay_order.mch_id
        trade_status = 'success'
        total_fee = float(pay_order.total_fee)
        trade_no = ''

        extend = {
            'trade_status': trade_status,
            'total_fee': total_fee,
            'trade_no': trade_no,
        }

        # 入款状态（W - 待入款，S - 入款成功）
        if response.text == 'success':
            _LOGGER.info('tengpay query order success, mch_id:%s pay_id:%s' % (mch_id, pay_order.id))
            order_db.add_pay_success(pay_order.mch_id, pay_order.id,
                                     total_fee, trade_no, extend)

            async_job.notify_mch(pay_order.id)
